<?php
namespace control;
/*
*线边库存退库类
*/

class tempInventoryRefundClass extends adIndexClass
{
    private const page = 'tempInventoryRefund';
    private const table = 'line_inventory_refund';
    private const tableMx = 'line_inventory_refund_detail';
    private const title = '线边库存退库';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'line'  => [
                        'name'  => '生产线',
                        'width' => 300,
                    ],
                    'num'         => [
                        'name'  => '数量',
                        'width' => 300,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "生产线"   => selectMultiple(["name" => "lineId", 'table' => "product_line", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name']),
                    '单据日期' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            "lineId" => $this->post('lineId'),
            'coid' => self::$coid,
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'line':
                        $line = query('product_line', "id = '$array[lineId]'");
                        $row[] = $line['workshop'] . '-' . $line['name'];
                        break;
                    case 'num':
                        $total = find(array('table' => self::tableMx, 'field' => "sum(any_value(num)) as num", 'single' => "orderId = '$array[id]' group by orderId"));
                        $row[] = self::lostZero($total['num'], 'numPrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx,
            'single' => " orderId in (select id from ".self::table." where 1=1 {$where}) ",
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $button[] = [
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        //仓库
        $result = find(array('table' => 'warehouse', 'field' => 'id,name', 'where' => "coid = '" . self::$coid . "' and state = '启用' order by time desc"));
        $tr[] = [
            '',
            '物料编码',
            '物料名称',
            '规格型号',
            '单位',
            "<div class='warehouse'><span class='word'>仓库</span>&emsp;" . self::chooseSelect($result['array'], 'warehouseId[]', 'warehouse') . "</div>",
            '库存',
            '批次',
            '数量',
            '备注'
        ];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($result['array'] as $k=>$array) {
            $material = query('material', " id = '$array[materialId]'");
            $unitOption = machiningOrderClass::unitOption($material['id']);
            $stockNum = tempInventoryClass::inventoryNum($array['materialId'], $array['unit'], $info['lineId']);
            $tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])),
                $material['code'],
                $material['name'],
                $material['model'],
                select(array(
                    'name' => 'unitDetail[]',
                    'data' => ['unit' => $array['unit']],
                    'change' => 'unitChange',
                    'option' => $unitOption,
                    'title' => '单位',
                    'value' => $array['unit']
                )),
                idSelect(array(
                    'name' => 'warehouseId[]',
                    'sqlForm' => "warehouse where coid = '" . self::$coid . "' and state = '启用' order by time desc",
                    'sqlId' => 'id',
                    'sqlField' => "name",
                    'title' => '仓库',
                    'value' => $array['warehouseId']
                )),
                "<span class='stockNum'>$stockNum</span>",
                text(array('name' => 'batch[]', 'value' => $array['batch'])),
                text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision')." onblur=\"calculateTotal()\" ", 'value' => self::lostZero($array['num'], 'numPrecision'))),
                text(array('name' => 'mxText[]', 'value' => $array['text'])),
            ];
        }
        $total      = [
            8  => "<span id='total_num'>" . self::lostZero(array_sum(array_column((array)$result['array'],'num')),'num') . "</span>",
        ];
        $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $but = <<<efo
                <span class="smallButton" onclick="chooseOrder()">选择产品</span>
efo;
        $line = query('product_line', "id = '$info[lineId]'");
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "单据日期：" => text(["name" => "recordDate", 'class' => 'text', 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    must . "生产线：" => repeatSelect(array(
                            'name' => 'workshop',
                            'title' => '生产车间',
                            'change' => "getLine",
                            'sqlForm' => "product_line where coid = '" . self::$coid . "' and state = '启用'",
                            'sqlField' => 'workshop',
                            'value' => $line['workshop']
                        )) .
                        idSelect(array(
                            'name' => 'lineId',
                            'sqlForm' => "product_line where coid = '" . self::$coid . "' and state = '启用' and workshop = '$line[workshop]'",
                            'sqlId' => 'id',
                            'sqlField' => 'name',
                            'title' => '生产线',
                            'value' => $info['lineId']
                        )),

                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '订单明细',
            'button' => $but,
            'html' => $list,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= <<<efo
<script>
function chooseOrder(){
    let lineId = $("[name='lineId']").val();
    if (!lineId){
        msg('请先选择生产线','error');
        return false;
    }
    layer('{$this->get('cla')}','addMx',$('form[name=tempInventoryRefundEditForm]').serialize())
}
//获取生产线
function getLine(e){
     let val = e.value;
     $.post(root+'control/adIndex.html?cla=machiningOrder&fun=getLine',{val:val},function(res) {
             $("select[name='lineId']").html(res.html);
        },'json');
}
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
        calculateTotal()
    },'json');
}
//计算计划数量
function calculateTotal(table=''){
    table = table ? table : $('.editList')
    let num = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
}
//根据单位转换所需数量和库存
function unitChange(e){
    let unit = e.value;
    if (!unit){
        msg('请选择单位')
        return '';
    }
    let oldUnit = $(e).data('unit');
    $(e).data('unit',unit);
    let lineId = $("[name='lineId']").val();
    let num = $(e).parent().parent().find("[name='num[]']").val();
    let id = $(e).parent().parent().find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=unitChange',{unit:unit,oldUnit:oldUnit,num:num,id:id,lineId:lineId},function(res) {
        if (res.warn==2){
            $(e).parent().parent().find("[name='num[]']").val(res.num);
            $(e).parent().parent().find(".stockNum").html(res.inventoryNum);
        }else{
            msg(res.warn);
        }
    },'json');
}
</script>

efo;
        //返回
        return $this->tab($data);
    }


    /**
     * 根据单位显示所需数量
     */
    public function unitChange()
    {
        $materialId = $this->post('id');
        $num = $this->post('num');
        $unit = $this->post('unit');
        $lineId = $this->post('lineId');
        $oldUnit = $this->post('oldUnit');
        if (empty($materialId)) {
            $json['warn'] = '未找到物料';
        } elseif (empty($unit)) {
            $json['warn'] = '未找到单位';
        } elseif (empty($lineId)) {
            $json['warn'] = '未找到生产线';
        } else {
            $json['warn'] = 2;
            $json['num'] = $num;
            if ($oldUnit) {
                $num = machiningOrderClass::material_num_change($materialId, $oldUnit, $unit, $num);
                $json['num'] = $num;
            }
            $inventoryNum =self::lostZero(tempInventoryClass::inventoryNum($materialId, $unit,$lineId), 'numPrecision');
            $json['inventoryNum'] = $inventoryNum;
        }
        return json_encode($json, 320);
    }
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $materialIdArr = $this->post('materialId');
        $numArr = $this->post('num');
        $unitArr = $this->post('unitDetail');
        $batchArr = $this->post('batch');
        $mxTextArr = $this->post('mxText');
        $warehouseIdArr = $this->post('warehouseId');
        $field = [
            'text' => $this->post('text'),
            'lineId' => $this->post('lineId'),
            'recordDate' => $this->post('recordDate'),
        ];
        $annotation = [
            'lineId' => '生产线',
            'recordDate' => '单据日期',
        ];
        $rules = [
            'lineId' => 'required',
            'recordDate' => 'required|date',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择订单明细';
        } elseif (static::is_null_array($materialIdArr)) {
            $json['warn'] = '请选择订单明细';
        } elseif (static::is_null_array($numArr)) {
            $json['warn'] = '数量请填写完整';
        } elseif (static::is_null_array($unitArr)) {
            $json['warn'] = '请选择单位';
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = '此线边库存退库已确认，不能修改';
        } else {
            $json['warn'] = '';

            if (empty($json['warn'])) {
                $this->startTrans();
                if (!$info['id']) {
                    $userNo = codeTemplateClass::generateCode(self::page, [
                        'prefix' => 'XBTK' . date('Ymd', strtotime($field['recordDate'])),
                        'table' => self::table,
                        'field' => 'orderNo',
                        'where' => " and coid = '" . self::$coid . "'",
                    ], $field);
                    $field = array_merge($field, [
                        'id' => $id,
                        'orderNo' => $userNo,
                        'state' => '草稿',
                        'coid' => self::$coid,
                        'stid' => $this->control['stid'],
                    ]);
                    $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
                } else {
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where,
                    ]);
                }

                //添加或更新明细
                if (is_array($mxIdArr)) {
                    foreach ($mxIdArr as $k => $nid) {
                        $mx = query(self::tableMx, "id = '$nid'");
                        $numArr[$k] = self::formattingFigure($numArr[$k], 'numPrecision');
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::tableMx,
                                "field" => [
                                    'materialId' => $materialIdArr[$k],
                                    'unit' => $unitArr[$k],
                                    'num' => $numArr[$k],
                                    'batch' => $batchArr[$k],
                                    'warehouseId' => $warehouseIdArr[$k],
                                    'text' => $mxTextArr[$k],
                                ],

                                "where" => " id = '$nid'",
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::tableMx,
                                "field" => [
                                    'id' => $nid,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'materialId' => $materialIdArr[$k],
                                    'unit' => $unitArr[$k],
                                    'num' => $numArr[$k],
                                    'warehouseId' => $warehouseIdArr[$k],
                                    'text' => $mxTextArr[$k],
                                    'batch' => $batchArr[$k],
                                ],

                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }
                if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                    $this->commitTrans();
                    delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                    if ($json['warn'] == '新增成功') {
                        auditClass::operateRecord($id, '线边库存退库', '新建');
                    }
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                } else {
                    $this->rollback();
                }
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * @return bool|string
     */
    public function addMx()
    {
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $html =
            materialClass::typeSelect() .
            text(array("name" => "code", "title" => "产品编码")) .
            text(array("name" => "materialName", "title" => "产品名称")) .
            text(array("name" => "model", "title" => "规格型号")) .
            hidden(array("name" => "lineId", "value" => $this->post('lineId'))) .
            hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : ''));
        $button = "<input onclick=\"addRow();removeSelectedContent('" . $formName . "')\" class='button' type='button' value='继续添加'>";
        $button .= "<input class='button m-l-5' onclick=\"addRow();$('#" . $layerId . "').remove()\" type='button' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 900, "html" => $html, "button" => $button));
    }

    /**
     *添加产品
     */
    public function addMxSearch()
    {
//        $materialId = $this->post('materialId') ? explode(',', $this->post('materialId')) : [];
//        $and = " and a.materialId not in ('" . implode("','", $materialId) . "')";
        $like = [
            'b.name' => $this->post('materialName'),
            'b.code' => $this->post('code'),
            'b.model' => $this->post('model'),
            'b.typePath' => $this->post('materialTypeId'),
        ];
        $equal = [
            'b.state' => '启用',
            'a.coid' => self::$coid,
        ];
        $where = search(["like" => $like, "=" => $equal]);
        $page = $this->page([
            "table" => "(select lineId,materialId,b.code,b.name,b.model,b.unit,b.subject,a.num from line_inventory as a join material as b on a.materialId = b.id where 1=1 $where order by a.time desc) as cc",
            'field' => "materialId,lineId,any_value(code) as code,any_value(name) as name,any_value(model) as model,any_value(unit) as unit,any_value(subject) as subject,ifnull(sum(any_value(num)),0) as num",
            "where" =>  ' 1=1  group by lineId,materialId having sum(any_value(num)) >0'
        ]);
        $materialObj = new materialClass();
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[] = [$checkAll, '分类', '产品编码', '产品名称', '规格型号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['materialId']),
            );
            $checkBox = $this->dominate($dominate);
            $material = query('material',"id = '$array[materialId]'");
            $tr[] = array(
                $checkBox,
                $material['typeName'],
                $material['code'],
                $material['name'],
                $material['model'],
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
                hidden(array("name" => "id", "value" => $this->post('id'))) .
                hidden(array("name" => "lineId", "value" => $this->post('lineId'))) .
                $this->tableMany(array("tr" => $tr)) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        $lineId = $this->post('lineId');      //客户ID
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择产品';
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $material = query('material', "id = '$mxId'");
                $num = tempInventoryClass::inventoryNum($mxId, $material['unit'], $lineId);
                $suiji = self::getId();
                $unitOption = machiningOrderClass::unitOption($material['id']);
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $suiji)) .
                    hidden(array('name' => 'materialId[]', 'value' => $mxId)),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    select(array(
                        'name' => 'unitDetail[]',
                        'data' => ['unit' => $material['unit']],
                        'change' => 'unitChange',
                        'option' => $unitOption,
                        'title' => '单位',
                        'value' => $material['unit']
                    )),
                    idSelect(array(
                        'name' => 'warehouseId[]',
                        'sqlForm' => "warehouse where coid = '" . self::$coid . "' and state = '启用' order by time desc",
                        'sqlId' => 'id',
                        'sqlField' => "name",
                        'title' => '仓库',
                        'value' => $material['warehouse']
                    )),
                    "<span class='stockNum'>$num</span>",
                    text(array('name' => 'batch[]')),
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision')." onblur=\"calculateTotal()\" ", 'value' => self::lostZero($num, 'numPrecision'))),
                    text(array('name' => 'mxText[]')),
                ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];

            if ($info['state'] != '已确认') {
                if ($this->power(self::page, "edit")) {
                    if ($info['state'] == '草稿') {
                        //按钮
                        $button[] = [
                            "name" => "提交",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "operate",
                            "post" => ["act" => 'commit', "id" => $info['id']],
                            'style' => 'li-btn-blue-bg',
                        ];
                    }
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑用户",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],

                    ];
                }


                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }
            //按钮
            $button[] = [
                "name" => "打印",
                "type" => "点击事件",
                "fun" => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
            ];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "确认",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "cancel") && $info['state'] == '已确认' && !$info['isClose']) {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $line = query('product_line', "id = '$info[lineId]'");
            $tr[] = ['物料编码', '物料名称', '规格型号', '单位', '仓库', '库存', '批次', '数量', '备注'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $warehouse = query('warehouse', "id = '$array[warehouseId]'");
                $tr[] = [
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    $warehouse['name'],
                    tempInventoryClass::inventoryNum($array['materialId'], $array['unit'], $info['lineId']),
                    $array['batch'],
                    self::lostZero($array['num'], 'numPrecision'),
                    $array['text'],
                ];
            }
            $total = find(array('table' => self::tableMx, 'field' => "sum(any_value(num)) as num", 'single' => "orderId = '$info[id]' group by orderId"));
            $total['num'] = $total['num'] ?? 0;
            $total_tr = [
                    7=>self::lostZero($total['num'], 'numPrecision')
            ];

            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "单据日期" => self::null($info['recordDate']),
                        "生产线" => $line['workshop'] . '-' . $line['name'],
                        "单据编号" => $info['orderNo'],
                        "制单人" => self::findStaff($info['stid']),
                    ),
                    array(
                        "状态" => $info['state']
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),

                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '退库明细',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time,
        ];
        $warn = '';

        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此线边库存退库';
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此线边库存退库不是待确认状态，不能确认';
        } elseif ($warn) {
            $json['warn'] = $warn;
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            $bool = $this->insertInventory($info['id']);
            if ($bool !== true) {
                $json['warn'] = $bool;
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                auditClass::operateRecord($id, '线边库存退库', '确认');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 生成入库单
     */
    private function insertInventory($info): bool|string
    {
        $re_array = [];//根据仓库重新分组
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
        foreach ($result['array'] as $array) {
            $re_array[$array['warehouseId']][] = $array['id'];
        }
        $supplier = query('supplier',"id = '$info[supplierId]'");
        $index = 1;
        foreach ($re_array as $warehouseId => $array) {

            $id = self::getId();
            $field = [
                'id' => $id,
                'type' => '线边库存退库',
                'coid' => self::$coid,
                'sourceTable' => self::table,
                'sourceId' => $info['id'],
                'warehouseId' => $warehouseId,
                'targetId' => $info['lineId'],
                'classify' => 1,
                'state' => '待入库',
                'workFlow'=>'已质检',
                'stid' => self::$stid,
                'orderDate'=>$this->date,
                'sourceDate'=>$info['recordDate'],
                'sourceNo'=>$info['orderNo'],
                'sourceTargetName'=>$supplier['name'],
            ];
            $userNo = codeTemplateClass::generateCode('inStock',[
                'prefix' => 'KCRK' . date('Ymd'),
                'table' => 'inventory',
                'field' => 'orderNo',
                'where' => " and coid = '".self::$coid."'",
                'index'=>$index
            ],$field);
            $index++;
            $field['orderNo'] = $userNo;
            $warn = static::insert(array(
                'table' => 'inventory',
                'field' => $field
            ));
            if ($warn != '新增成功') {
                return "新增入库单失败";
            }
            foreach ($array as $mxId) {
                $mx = query(self::tableMx, "id = '$mxId'");
                $inventoryMxId = self::getId();
                $warn = static::insert(array(
                    'table' => 'inventory_detail',
                    'field' => [
                        'id' => $inventoryMxId,
                        'coid' => self::$coid,
                        'sourceTable' => self::tableMx,
                        'sourceId' => $mx['id'],
                        'materialId' => $mx['materialId'],
                        'warehouseId' => $warehouseId,
                        'unit' =>$mx['unit'],
                        'orderId' => $id,
                        'orderNum' => $mx['num'],
                    ]
                ));
                if ($warn != '新增成功') {
                    return "新增入库单明细失败";
                }
            }
        }
        return true;
    }


    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => '',
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此线边库存退库';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此线边库存退库不是已确认状态，无需撤回';
        } elseif (static::total(array('table' => 'inventory', "where" => "sourceId = '$info[id]' and coid = '" . self::$coid . "' and state in ('部分入库','已入库')")) > 0) {
            $json['warn'] = '此线边库存退库已存在有入库的单据，不能撤回';
        }  else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                //删除入库单
                delete(array('table' => 'inventory_detail', 'where' => "orderId in (select id from inventory where sourceId = '$info[id]' and coid = '" . self::$coid . "')"));
                delete(array('table' => 'inventory', 'where' => "sourceId = '$info[id]'"));
                auditClass::operateRecord($id, '线边库存退库', '撤回');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];

        $warn = '';
        //库存可用量控制
        $result = find(array('table' => self::tableMx, "where" => "orderId = '$id' order by list asc"));
        $tempResult = [];
        //判断库存是否可领料,首先需要相同物料分组，避免只判断一个物料够不够
        foreach ($result['array'] as $array) {
            $tempResult[$array['materialId']][] = [
                'id' => $array['id'],
                'unit' => $array['unit'],
                'num' => $array['num'],
            ];
        }
        foreach ($tempResult as $materialId => $array) {
            $material = query('material', "id = '$materialId'");
            //当前可用库存
            $inventoryNum = tempInventoryClass::inventoryNum($materialId, $material['unit'], $info['lineId']);
            $num = 0;
            foreach ($array as $val) {
                //占用库存
                $num += machiningOrderClass::material_num_change($materialId, $val['unit'], $material['unit'], $val['num']);
            }
            if (self::formattingFigure($num,'numPrecision') > self::formattingFigure($inventoryNum,'numPrecision')) {
                $warn = "物料【{$material['name']}】退料数量已超出线边库存数量";
                break;
            }
        }

        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此线边库存退库';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此线边库存退库不是草稿状态，不能提交';
        } elseif ($warn) {
            $json['warn'] = $warn;
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditClass::operateRecord($id, '线边库存退库', '提交');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此线边库存退库，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此线边库存退库？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此线边库存退库？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }


	/**
	 * 批量打印
	 *
	 * @return string
	 */
	public function batchPrint(): string
	{
		$lists = $this->get('lists');
		if(empty($lists)){
			exit('参数错误');
		}else{
			$listId = base64_decode($lists, true);
			$array = explode(',', $listId);
			$data = [];
			foreach ($array as $id){
				$data[] = static::printPage($id, false);
			}
			return (new printTemplateClass())->start(self::page, $data);
		}
	}

	/**
	 * 打印
	 *
	 * @return string
	 */
	public function printPage($param = '', $isReturn = true): string|array
	{
		$id                  = $param ?: $this->get('id');
		$info                = query(self::table, " id = '$id'");
        $info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
        $info['title'] = self::title;
        $info['printTime'] = $this->time;
        $info['stid'] = self::findStaff($info['stid']);
        $info['checkId'] = self::findStaff($info['checkId']);
        $info['khName'] = query('kehu', "khid = '$info[khid]'")['companyName'];
        $info['qr'] = "source=" . self::table . "&id=" . $info['id'];
        $info['salemans'] = self::findStaff($info['manager']);
        $info['tags'] = orderTagClass::getTagName($info['id']);
        $detail = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
        $items = [];
        $x = 1;
        $totalNum = 0;
        $totalMoney = 0;
        foreach ($detail as $array) {
            $material = query('material', "id = '$array[materialId]'");
            $items[] = [
                'no' => $x,
                'materialCode' => $material['code'],
                'materialName' => $material['name'],
                'price' => self::lostZero($array['price'], 'pricePrecision'),
                'rate' => ($array['rate'] * 100) . '%',
                'taxMoney' => self::lostZero($array['taxMoney'], 'amount'),
                'khMaterialName' => $array['khMaterialName'],
                'khMaterialCode' => $array['khMaterialCode'],
                'moneyWithOutTax' => self::formattingFigure($array['money'] - $array['taxMoney'], 'amount'),
                'money' => self::lostZero($array['money'], 'amount'),
                'model' => $material['model'],
                'unit' => $array['unit'],
                'num' => $array['num'],
                'text' => $array['text'],
            ];
            $x++;
            $totalNum += $array['num'];
            $totalMoney += $array['money'];
        }
        $append = [
            'no' => '合计',
            'num' => self::lostZero($totalNum, 'amount'),
            'money' => self::lostZero($totalMoney, 'amount'),
        ];
        $items[] = $append;
        $info['detail'] = $items;
	    if ($isReturn) {
		    return (new printTemplateClass())->start(self::page, $info);
	    } else {
		    return $info;
	    }
    }
}

